package deng.qiya.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import deng.qiya.model.WeChatHomeinnsUser;
import deng.qiya.util.CustomerContextHolder;
import deng.qiya.wechat.Constant;

public class WeChatHomeinnsUserOper {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public WeChatHomeinnsUser getUserByWeChatUser(String weChatUserName){
		String sql = "SELECT  [ID]      ,[WECHAT_USER]      ,[PHONE]      ,[IDENTI]      ,[SYSTEM_TIME]  FROM [WECHAT_HOMEINN_USER] WHERE WECHAT_USER=?";
		Object[] params = new Object[]{weChatUserName};
		CustomerContextHolder.setCustomerType(Constant.ds);
		List<WeChatHomeinnsUser> list = jdbcTemplate.query(sql,params,new WeChatHomeinnsUserMapper());
		if(list !=null && list.size()>0){
			return list.get(0);
		}
		else{
			return null;
		}
	}
	
	public int newWeChatHomeinnUser(WeChatHomeinnsUser weChatHomeinnsUser)
	{
		WeChatHomeinnsUser hasUser = getUserByWeChatUser(weChatHomeinnsUser.getWeChatUser());
		String sql = "";
		CustomerContextHolder.setCustomerType(Constant.ds);
		if(hasUser == null){
			 sql = "INSERT INTO [WECHAT_HOMEINN_USER]           ([WECHAT_USER]           ,[PHONE]           ,[IDENTI]           ,[SYSTEM_TIME])     VALUES" +
					"(?,?,?,?)";
				Object[] parms = new Object[]{weChatHomeinnsUser.getWeChatUser(),
						weChatHomeinnsUser.getPhone(),
						weChatHomeinnsUser.getIdenti(),
						weChatHomeinnsUser.getSystemTime()};
				
				jdbcTemplate.update(sql, parms);
				return jdbcTemplate.queryForInt("select @@identity");
		}
		else{
			sql = "UPDATE [WECHAT_HOMEINN_USER] SET WECHAT_USER=?,IDENTI=?, SYSTEM_TIME=? WHERE PHONE=?";
			Object[] parms = new Object[]{weChatHomeinnsUser.getWeChatUser(),
					weChatHomeinnsUser.getIdenti(),
					weChatHomeinnsUser.getSystemTime(),
					weChatHomeinnsUser.getPhone()};
			jdbcTemplate.update(sql,parms);
			return hasUser.getId();
		}
	}
	
	
	
	class WeChatHomeinnsUserMapper implements RowMapper<WeChatHomeinnsUser>{

		@Override
		public WeChatHomeinnsUser mapRow(ResultSet rs, int rowNum) throws SQLException {
			WeChatHomeinnsUser user = new WeChatHomeinnsUser();
			user.setId(new Integer(rs.getString("ID")));
			user.setWeChatUser(rs.getString("WECHAT_USER"));
			user.setPhone(rs.getString("PHONE"));
			user.setIdenti(rs.getString("IDENTI"));
			user.setSystemTime(rs.getTimestamp("SYSTEM_TIME"));
			return user;
		}
		
	}
}
